using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Util;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;

namespace Admin.NET.Application.Extension;

public static class CertExtension
{
	public static void AddCert(this IServiceCollection services)
	{
		using ServiceProvider build = services.BuildServiceProvider();
		string rootUrl = AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "ssl";
		string wwwroot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");
		using ISqlSugarClient platConfig = build.CreateScope().ServiceProvider.GetService<ISqlSugarClient>();
		List<PlatformConfig> list = platConfig.Queryable<PlatformConfig>().ToList();
		foreach (PlatformConfig input in list)
		{
			if (string.IsNullOrEmpty(input.WebUrl) || string.IsNullOrEmpty(input.SslPwd) || string.IsNullOrEmpty(input.SslUrl))
			{
				continue;
			}
			try
			{
				Uri uri = new Uri(input.SslUrl);
				string path = uri.LocalPath;
				string text = path;
				path = text.Substring(1, text.Length - 1);
				string sslPath = Path.Combine(wwwroot, path);
				if (File.Exists(sslPath))
				{
					byte[] bytearry = File.ReadAllBytes(sslPath);
					X509Certificate2 x509Certificate2 = new X509Certificate2(bytearry, input.SslPwd);
					UtilCertDic.SetCertDic(input.WebUrl, x509Certificate2);
				}
			}
			catch (Exception)
			{
			}
		}
	}
}
